import {messages} from "share/common";
import React from 'react';
import { connect } from 'react-redux';
import errorMessage from 'share/errorMessage';
import menuRoute from 'routes/menuRoute'
import { message, Button, Popconfirm, Icon, Badge, Popover } from 'antd';
import ResizeTable from 'components/resize-table'
import SlideFrame from 'components/slide-frame'
import NewScene from 'containers/expense-reimbursement-control/expense-standard/travel-policy/new-scene'
import travelPolicyService from 'containers/expense-reimbursement-control/expense-standard/travel-policy/travel-policy.service'

class DiningScene extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      data: [], //用餐类型数据
      page: 0,
      pageSize: 10,
      pagination: {
        current: 0,
        total: 0
      },
      columns: [
        {title: messages('common.sequence'), dataIndex: 'index', width: '5%',render: (value, record, index) => index + 1 + this.state.pageSize * this.state.page},
        {title: messages('expense-reimbursement-control.key98')/*用餐类型*/, dataIndex: 'name', width: '20%'},
        {title: messages('expense-reimbursement-control.key99')/*适用表单*/, dataIndex: 'visibleForms', width: '40%',
          render: (value, record) => {
            if (value && value.length) {
              let formNameList = [];
              value.map(form => {
                formNameList.push(form.formName);
              });
              return <Popover placement="topLeft" content={formNameList.join(',')}>{formNameList.join(',')}</Popover>
            } else {
              return <div>{messages('expense-reimbursement-control.key28')/*通用*/}</div>
            }
          }
        },
        {title: messages('common.column.status'), dataIndex: 'status', width: '10%', align: "right",
          render: (value, record) => (
            <Badge
              status={value === 1 ? 'success' : 'error'}
              text={value === 1 ? messages('common.enabled') : messages('common.disabled')}
            />
          )
        },
        {title: messages('common.operation'), dataIndex: 'operation', key: 'operation',"align":"center",
          render: (text, record) => (
            <span>
              <a onClick={(e) => this.handleEdit(e, record)}>{messages('common.edit')}</a>
              <span className="ant-divider"/>
              <Popconfirm onConfirm={(e) => this.handleDelete(e, record)} title={messages('setting.key1189'/*你确认要删除？*/)}>
                <a onClick={(e) => {e.preventDefault(); e.stopPropagation();}}>{messages('common.delete')}</a>
              </Popconfirm>
            </span>
          )
        }
      ],
      showSlideFrame: false, //编辑用餐类型的侧拉框是否弹出
      nowScene: {}, //编辑用餐类型的侧拉框里所用的参数
    };
    this.sceneDetail = menuRoute.getRouteItem('dining-detail', 'key');
    this.travelStandard = menuRoute.getRouteItem('expense-standard', 'key');
  }

  componentDidMount(){
    this.getSceneList();
  }

  getSceneList = () => {
    const { params } = this.props;
    const { page, pageSize } = this.state;
    this.setState({loading: true});
    travelPolicyService.getSceneList(page, pageSize, params.travelItineraryStandID).then(res => {
      this.setState({
        data: res.data,
        loading: false,
        pagination: {
          current: page + 1,
          total: Number(res.headers['x-total-count']),
          onChange: this.onChangePager
        }
      });
    }).catch(e => {
      this.setState({loading: false});
      errorMessage(e.response);
    });
  };

  //点击分页
  onChangePager = (page) => {
    const { page: currentPage } = this.state;
    if (page - 1 !== currentPage) {
      this.setState({page: page - 1}, this.getList);
    }
  };

  handleDelete = (e, record) => {
    this.setState({loading: true});
    travelPolicyService.deleteDiningScene(record.id).then(res => {
      this.setState({loading: false});
      message.success(messages('setting.key213'/*删除成功*/));
      this.getSceneList();
    }).catch(e => {
      this.setState({loading: false});
      errorMessage(e.response);
    });
  };

  handleBack = () => {
    this.context.router.push(`${this.travelStandard.url}`);
  };

  handleOnClose = () => {
    this.setState({
      showSlideFrame: false,
      nowScene: {
        showSlideFrame: false
      }
    });
  };

  //isSuccess是否是保存成功的关闭，如果是，则要刷新用餐类型列表
  handleCloseSlide = (isSuccess) => {
    isSuccess && this.getSceneList();
    this.setState({
      showSlideFrame: false,
      nowScene: {
        showSlideFrame: false
      }
    });
  };

  //新建
  handleNewScene = () => {
    const { params } = this.props;
    this.setState({
      showSlideFrame: true,
      nowScene: {
        showSlideFrame: true,
        id: params.id,
        setOfBooksId: params.setOfBooksId,
        travelItineraryStandID: params.travelItineraryStandID
      }
    });
  };

  //编辑
  handleEdit = (e, record) => {
    const { params } = this.props;
    e.preventDefault();
    e.stopPropagation();
    this.setState({
      showSlideFrame: true,
      nowScene: {
        showSlideFrame: true,
        id: params.id,
        setOfBooksId: params.setOfBooksId,
        travelItineraryStandID: params.travelItineraryStandID,
        record: record
      }
    });
  };

  //跳转到用餐类型详情页
  handleRowClick = (record) => {
    const { params, tenantMode } = this.props;
    let url = '';
    url = this.sceneDetail.url.replace(':travelItineraryStandID', params.travelItineraryStandID).replace(':id', params.id).replace(':sceneId', record.id);
    if (tenantMode) {
      url = url.replace(':setOfBooksId', params.setOfBooksId);
    }
    this.context.router.push(url);
  };

  render() {
    const { loading, columns, data, pagination, showSlideFrame, nowScene } = this.state;
    return (
      <div>
        <div className="header-title">
          {messages('expense-reimbursement-control.key100')/*用餐类型定义*/}
        </div>
        <Button type="primary" style={{marginBottom: 24}} onClick={this.handleNewScene}>{messages('expense-reimbursement-control.key101')/*新增类型*/}</Button>
        <ResizeTable
          columns={columns}
          dataSource={data}
          pagination={pagination}
          loading={loading}
          rowKey={record => record.id}
          onRow={record => ({onClick: () => this.handleRowClick(record)})}
          bordered
          size="middle"
        />
        <a style={{fontSize:'14px', display: 'inline-block', marginTop: 10}} onClick={this.handleBack}>
          <Icon type="rollback" style={{marginRight:'5px'}}/>{messages('common.back')}
        </a>
        <SlideFrame
          content={NewScene}
          title={messages('expense-reimbursement-control.key98')/*用餐类型*/}
          show={showSlideFrame}
          onClose={this.handleOnClose}
          afterClose={this.handleCloseSlide}
          params={nowScene}
        />
      </div>
    )
  }
}

DiningScene.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    tenantMode: state.main.tenantMode
  }
}

DiningScene.propTypes = {};

DiningScene.defaultProps = {};

export default connect(mapStateToProps)(DiningScene);
